package com.pan.picture.impl;

import com.pan.interfere.Interfere;
import com.pan.interfere.impl.CodeInterfere;
import com.pan.picture.Picture;
import com.pan.utils.RandomColor;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.stream.Collectors;

public class CodePicture implements Picture {

    private List<CharPicture> charPictureList;

    private BufferedImage bgImage;

    private Graphics2D graphics;

    private Interfere codeInterfere;

    public CodePicture(List<CharPicture> charPictureList){
        this.charPictureList = charPictureList;
        bgImage = null;

    }

    public CodePicture(char[] chars) {
        this(String.valueOf(chars).chars().mapToObj(c->new CharPicture((char) c)).collect(Collectors.toList()));
    }
    public CodePicture(){}

    @Override
    public void createImage(){
        if (charPictureList == null||charPictureList.size()==0){
            throw new RuntimeException("请设置验证码内容");
        }
        CharPicture charPicture = charPictureList.get(0);
        int width = charPicture.getImage().getWidth()*charPictureList.size();
        int height = charPicture.getImage().getHeight();
        if (bgImage==null||graphics == null) {
            bgImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            graphics = bgImage.createGraphics();
            codeInterfere = new CodeInterfere(bgImage);
        }
        graphics.setBackground(RandomColor.getBackgroundColor());
        graphics.clearRect(0,0,width,height);
        int innerWidth =charPicture.getImage().getWidth();
        int innerHeight = charPicture.getImage().getHeight();
        for (int i = 0; i < charPictureList.size(); i++) {
            BufferedImage bufferedImage = charPictureList.get(i).getImage();
            graphics.drawImage(bufferedImage,0+innerWidth*i,0,innerWidth,innerHeight,null);
        }
    }


    @Override
    public BufferedImage getImage() {
        if (bgImage==null) {
            createImage();
        }
        return bgImage;
    }

    @Override
    public void reset(String str){
        this.charPictureList = str.chars()
                .mapToObj(c->new CharPicture((char) c))
                .collect(Collectors.toList());
        createImage();
    }

    @Override
    public void interfere() {
        charPictureList.forEach(Picture::interfere);
        createImage();
        codeInterfere.drawInterfere();
    }

    @Override
    public void close(){
        charPictureList.stream().forEach(Picture::close);
        graphics.dispose();
        codeInterfere.close();
    }

}
